import { defineComponent, PropType, ref } from 'vue'
import {
  NButton,
  NDataTable,
  NDivider,
  NDrawer,
  NDrawerContent,
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NLayout,
  NLayoutContent,
  NLayoutSider,
  NRadio,
  NRadioGroup,
  NSelect,
  NSpace,
  NTreeSelect
} from 'naive-ui'
import { DataXTaskLog } from '@/service/modules/task-manage/types'
import { useDatasource } from '@/views/data-manage/common/use-datasource'
import { useTable } from './use-table'
import { useColumns } from './use-columns'
import { getResTreeReq, runDataXReq } from '@/service/modules/task-manage'
import taskParamsConfig from '@/views/task-manage/tab/task-detail-tab/task-params-config'
import task from '@/locales/zh_CN/task'
const DataSyncTaskContent = defineComponent({
  name: 'DataSyncTaskContent',
  props: {
    taskLog: {
      type: Object as PropType<DataXTaskLog>,
      required: false
    }
  },
  setup() {
    //数据源类型下拉选项
    const {
      dsVariables: sourceDsVariables,
      getDsTypeOptions: getSourceDsTypeOptions,
      getDatasourceByType: getSourceDatasourceByType,
      getDbsByDatasourceId: getSourceDbsByDatasourceId,
      getTablesByDsAndDb: getSourceTablesByDsAndDb
    } = useDatasource()
    getSourceDsTypeOptions()
    const {
      dsVariables: targetDsVariables,
      getDsTypeOptions: getTargetDsTypeOptions,
      getDatasourceByType: getTargetDatasourceByType,
      getDbsByDatasourceId: getTargetDbsByDatasourceId,
      getTablesByDsAndDb: getTargetTablesByDsAndDb
    } = useDatasource()
    getTargetDsTypeOptions()
    const {
      state,
      getSourceTableDetail,
      getTargetTableDetail,
      onOperationClick
    } = useTable()
    const { columnsRef } = useColumns(state, onOperationClick)
    const resourceOption = ref([])
    const taskParamsDrawerRef = ref(false)
    return {
      sourceDsVariables,
      getSourceDatasourceByType,
      getSourceDbsByDatasourceId,
      getSourceTablesByDsAndDb,
      targetDsVariables,
      getTargetDatasourceByType,
      getTargetDbsByDatasourceId,
      getTargetTablesByDsAndDb,
      state,
      getSourceTableDetail,
      getTargetTableDetail,
      resourceOption,
      columnsRef,
      taskParamsDrawerRef
    }
  },
  watch: {
    taskLog() {
      if (this.taskLog) {
        this.state.taskLog = this.taskLog
        this.getSourceDatasourceByType(
          this.state.taskLog.taskContent.reader.dbType
        )
        this.getTargetDatasourceByType(
          this.state.taskLog.taskContent.writer.dbType
        )
        this.getSourceDbsByDatasourceId(
          this.state.taskLog.taskContent.reader.datasourceId
        )
        this.getTargetDbsByDatasourceId(
          this.state.taskLog.taskContent.writer.datasourceId
        )
        this.getSourceTablesByDsAndDb(
          this.state.taskLog.taskContent.reader.datasourceId,
          this.state.taskLog.taskContent.reader.dbName
        )
        this.getTargetTablesByDsAndDb(
          this.state.taskLog.taskContent.writer.datasourceId,
          this.state.taskLog.taskContent.writer.dbName
        )
        this.getSourceTableDetail()
        this.getTargetTableDetail().then(() => {
          this.state.fieldMaps.splice(0)
          this.state.taskLog.taskContent.reader.columns.forEach(
            (item, index) => {
              const targetColumn =
                this.state.taskLog.taskContent.writer.columns[index]
              this.state.fieldMaps.push({
                sourceColumnName: item.name,
                sourceDataType: item.type,
                sourceDataFormat: item.format,
                targetColumnName: targetColumn.name,
                targetDataType: targetColumn.type,
                targetDefVal: targetColumn.defVal
              })
            }
          )
        })
      }
    }
  },
  mounted() {
    this.getResourceTree()
  },
  methods: {
    onSaveTask() {},
    onReleaseTask() {},
    async onTmpExecTask() {
      this.state.taskLog.taskContent.reader.columns.splice(0)
      this.state.taskLog.taskContent.writer.columns.splice(0)
      this.state.fieldMaps.forEach((item) => {
        this.state.taskLog.taskContent.reader.columns.push({
          name: item.sourceColumnName,
          type: item.sourceDataType,
          format: item.sourceDataFormat
        })
        this.state.taskLog.taskContent.writer.columns.push({
          name: item.targetColumnName,
          defVal: item.targetDefVal,
          type: item.targetDataType
        })
      })
      await runDataXReq(this.state.taskLog)
    },
    onConfigTaskParams() {
      this.taskParamsDrawerRef = true
    },
    handleSourceDsTypeChange(value: string) {
      this.state.taskLog.taskContent.reader.datasourceId = null
      this.sourceDsVariables.dsOptions = []
      this.state.taskLog.taskContent.reader.dbName = null
      this.sourceDsVariables.dbOptions = []
      this.state.taskLog.taskContent.reader.tbName = null
      this.sourceDsVariables.tableOptions = []
      this.state.sourceTableInfo = {}
      this.getSourceDatasourceByType(value)
    },
    handleTargetDsTypeChange(value: string) {
      this.state.taskLog.taskContent.writer.datasourceId = null
      this.targetDsVariables.dsOptions = []
      this.state.taskLog.taskContent.writer.dbName = null
      this.targetDsVariables.dbOptions = []
      this.state.taskLog.taskContent.writer.tbName = null
      this.targetDsVariables.tableOptions = []
      this.state.targetTableInfo = {}
      this.getTargetDatasourceByType(value)
    },
    handleSourceDsChange(datasourceId: number) {
      this.state.taskLog.taskContent.reader.dbName = null
      this.sourceDsVariables.dbOptions = []
      this.state.taskLog.taskContent.reader.tbName = null
      this.sourceDsVariables.tableOptions = []
      this.state.sourceTableInfo = {}
      this.getSourceDbsByDatasourceId(datasourceId)
    },
    handleTargetDsChange(datasourceId: number) {
      this.state.taskLog.taskContent.writer.dbName = null
      this.targetDsVariables.dbOptions = []
      this.state.taskLog.taskContent.writer.tbName = null
      this.targetDsVariables.tableOptions = []
      this.state.targetTableInfo = {}
      this.getTargetDbsByDatasourceId(datasourceId)
    },
    handleSourceDbChange(dbName: string) {
      this.state.taskLog.taskContent.reader.tbName = null
      this.sourceDsVariables.tableOptions = []
      this.state.sourceTableInfo = {}
      this.getSourceTablesByDsAndDb(
        this.state.taskLog.taskContent.reader.datasourceId,
        dbName
      )
    },
    handleTargetDbChange(dbName: string) {
      this.state.taskLog.taskContent.writer.tbName = null
      this.targetDsVariables.tableOptions = []
      this.state.targetTableInfo = {}
      this.getTargetTablesByDsAndDb(
        this.state.taskLog.taskContent.writer.datasourceId,
        dbName
      )
    },
    handleSourceTableChange(tableName: string) {
      this.state.taskLog.taskContent.reader.tbName = tableName
      this.getSourceTableDetail()
    },
    handleTargetTableChange(tableName: string) {
      this.state.taskLog.taskContent.writer.tbName = tableName
      this.getTargetTableDetail()
    },
    async getResourceTree() {
      this.resourceOption = []
      const res = await getResTreeReq()
      if (res.resp_code === 0) {
        this.resourceOption = res.data
      }
    }
  },
  render() {
    return (
      <div id='taskContent'>
        <div
          id='taskContentHeader'
          style='flex:1;background-color: #ededef;padding:5px'
        >
          <NSpace justify='end' style='margin-right:20px'>
            <NButton type='info' size='tiny' onClick={this.onSaveTask}>
              {window.$t('taskManage.save')}
            </NButton>
            <NButton type='info' size='tiny' onClick={this.onReleaseTask}>
              {window.$t('taskManage.release')}
            </NButton>
            <NButton type='info' size='tiny' onClick={this.onTmpExecTask}>
              {window.$t('taskManage.tmpExec')}
            </NButton>
            <NButton type='info' size='tiny' onClick={this.onConfigTaskParams}>
              {window.$t('taskManage.configTaskParams')}
            </NButton>
          </NSpace>
        </div>
        <div style='height:calc(100% - 32.5px)'>
          <NSpace vertical>
            <NLayout hasSider>
              <NLayoutSider
                style='writing-mode:vertical-lr;font-size:16px;text-align:center;line-height:50px'
                width='50'
              >
                {window.$t('taskManage.selectDatasource')}
              </NLayoutSider>
              <NLayoutContent>
                <NSpace justify='space-around'>
                  <NForm style='margin:20px 10px' labelPlacement='left'>
                    <div style='text-align:center'>
                      {window.$t('taskManage.sourceTable')}
                    </div>
                    <NFormItem showFeedback={false}>
                      <NSelect
                        v-model:value={
                          this.state.taskLog.taskContent.reader.dbType
                        }
                        options={this.sourceDsVariables.dsTypeOptions}
                        size='small'
                        style='width:300px'
                        placeholder={window.$t('dataManage.datasourceTypeTips')}
                        onUpdateValue={this.handleSourceDsTypeChange}
                      />
                    </NFormItem>
                    <NFormItem
                      showFeedback={false}
                      v-show={
                        this.state.taskLog.taskContent.reader.dbType !== 'FILE'
                      }
                    >
                      <NSelect
                        v-model:value={
                          this.state.taskLog.taskContent.reader.datasourceId
                        }
                        options={this.sourceDsVariables.dsOptions}
                        filterable
                        size='small'
                        style='width:300px'
                        placeholder={window.$t(
                          'dataManage.selectDatasourceTips'
                        )}
                        onUpdateValue={this.handleSourceDsChange}
                      />
                    </NFormItem>
                    <NFormItem
                      showFeedback={false}
                      v-show={
                        this.state.taskLog.taskContent.reader.dbType !== 'FILE'
                      }
                    >
                      <NSelect
                        v-model:value={
                          this.state.taskLog.taskContent.reader.dbName
                        }
                        options={this.sourceDsVariables.dbOptions}
                        filterable
                        size='small'
                        style='width:300px'
                        placeholder={window.$t('dataManage.selectDbTips')}
                        onUpdateValue={this.handleSourceDbChange}
                      />
                    </NFormItem>
                    <NFormItem
                      showFeedback={false}
                      v-show={
                        this.state.taskLog.taskContent.reader.dbType !== 'FILE'
                      }
                    >
                      <NSelect
                        v-model:value={
                          this.state.taskLog.taskContent.reader.tbName
                        }
                        options={this.sourceDsVariables.tableOptions}
                        filterable
                        size='small'
                        style='width:300px'
                        placeholder={window.$t('dataManage.selectTableTips')}
                        onUpdateValue={this.handleSourceTableChange}
                      />
                    </NFormItem>
                    <NFormItem
                      label={window.$t('taskManage.whereCondition')}
                      showFeedback={false}
                      v-show={
                        this.state.taskLog.taskContent.reader.dbType !== 'FILE'
                      }
                    >
                      <NInput
                        type='textarea'
                        size='small'
                        rows={2}
                        v-model:value={
                          this.state.taskLog.taskContent.reader.where
                        }
                      />
                    </NFormItem>
                    <NFormItem
                      label={window.$t('taskManage.splitPk')}
                      showFeedback={false}
                      v-show={
                        this.state.taskLog.taskContent.reader.dbType !== 'FILE'
                      }
                    >
                      <NInput
                        type='text'
                        size='small'
                        placeholder={window.$t('taskManage.splitPk')}
                        v-model:value={
                          this.state.taskLog.taskContent.reader.splitPk
                        }
                      />
                    </NFormItem>
                    <NFormItem
                      showFeedback={false}
                      v-show={
                        this.state.taskLog.taskContent.reader.dbType === 'FILE'
                      }
                    >
                      <NTreeSelect
                        v-model:value={
                          this.state.taskLog.taskContent.reader.resourceId
                        }
                        options={this.resourceOption}
                        label-field='name'
                        key-field='id'
                        children-field='childs'
                        clearable
                        filterable
                        placeholder={window.$t('taskManage.selectFileTips')}
                      />
                    </NFormItem>
                    <NFormItem
                      label={window.$t('taskManage.encoding')}
                      showFeedback={false}
                      v-show={
                        this.state.taskLog.taskContent.reader.dbType === 'FILE'
                      }
                    >
                      <NInput
                        type='text'
                        size='small'
                        defaultValue='UTF-8'
                        v-model:value={
                          this.state.taskLog.taskContent.reader.encoding
                        }
                      />
                    </NFormItem>
                    <NFormItem
                      label={window.$t('taskManage.fieldDelimiter')}
                      showFeedback={false}
                      v-show={
                        this.state.taskLog.taskContent.reader.dbType === 'FILE'
                      }
                    >
                      <NInput
                        type='text'
                        size='small'
                        defaultValue=','
                        v-model:value={
                          this.state.taskLog.taskContent.reader.fieldDelimiter
                        }
                      />
                    </NFormItem>
                    <NFormItem
                      label={window.$t('taskManage.speedChannel')}
                      showFeedback={false}
                    >
                      <NInputNumber
                        size='small'
                        min={1}
                        style='width:100%'
                        v-model:value={
                          this.state.taskLog.taskContent.speedChannel
                        }
                      ></NInputNumber>
                    </NFormItem>
                  </NForm>

                  <NForm style='margin:20px 10px' labelPlacement='left'>
                    <div style='text-align:center'>
                      {window.$t('taskManage.targetTable')}
                    </div>
                    <NFormItem showFeedback={false}>
                      <NSelect
                        v-model:value={
                          this.state.taskLog.taskContent.writer.dbType
                        }
                        options={this.targetDsVariables.dsTypeOptions}
                        size='small'
                        style='width:300px'
                        placeholder={window.$t('dataManage.datasourceTypeTips')}
                        onUpdateValue={this.handleTargetDsTypeChange}
                      />
                    </NFormItem>
                    <NFormItem showFeedback={false}>
                      <NSelect
                        v-model:value={
                          this.state.taskLog.taskContent.writer.datasourceId
                        }
                        options={this.targetDsVariables.dsOptions}
                        filterable
                        size='small'
                        style='width:300px'
                        placeholder={window.$t(
                          'dataManage.selectDatasourceTips'
                        )}
                        onUpdateValue={this.handleTargetDsChange}
                      />
                    </NFormItem>
                    <NFormItem showFeedback={false}>
                      <NSelect
                        v-model:value={
                          this.state.taskLog.taskContent.writer.dbName
                        }
                        options={this.targetDsVariables.dbOptions}
                        filterable
                        size='small'
                        style='width:300px'
                        placeholder={window.$t('dataManage.selectDbTips')}
                        onUpdateValue={this.handleTargetDbChange}
                      />
                    </NFormItem>
                    <NFormItem showFeedback={false}>
                      <NSelect
                        v-model:value={
                          this.state.taskLog.taskContent.writer.tbName
                        }
                        options={this.targetDsVariables.tableOptions}
                        filterable
                        size='small'
                        style='width:300px'
                        placeholder={window.$t('dataManage.selectTableTips')}
                        onUpdateValue={this.handleTargetTableChange}
                      />
                    </NFormItem>
                    <NFormItem
                      showFeedback={false}
                      label={window.$t('taskManage.writeMode')}
                    >
                      <NRadioGroup
                        style='width:250px'
                        v-model:value={
                          this.state.taskLog.taskContent.writer.writeMode
                        }
                      >
                        <NRadio checked value='insert'>
                          insert
                        </NRadio>
                        <NRadio value='replace'>replace</NRadio>
                        <NRadio value='update'>update</NRadio>
                        <NRadio value='into'>into</NRadio>
                        <NRadio value='overwrite'>overwrite</NRadio>
                      </NRadioGroup>
                    </NFormItem>
                  </NForm>
                </NSpace>
              </NLayoutContent>
            </NLayout>
            <NDivider dashed={true} style='margin:5px 0' />
            <NLayout hasSider>
              <NLayoutSider
                style='writing-mode:vertical-lr;font-size:16px;text-align:center;line-height:50px'
                width='50'
              >
                {window.$t('taskManage.fieldMap')}
              </NLayoutSider>
              <NLayoutContent style='margin:10px 10px'>
                <NDataTable
                  row-class-name='items'
                  columns={this.columnsRef.columns}
                  size='small'
                  single-line={false}
                  data={this.state.fieldMaps}
                  scrollX={this.columnsRef.tableWidth}
                />
              </NLayoutContent>
            </NLayout>
          </NSpace>
        </div>
        <NDrawer
          v-model:show={this.taskParamsDrawerRef}
          width='400'
          placement='right'
          to='#taskContent'
        >
          <NDrawerContent native-scrollbar={false}>
            {taskParamsConfig['DATAX'](this.state.taskLog)}
          </NDrawerContent>
        </NDrawer>
      </div>
    )
  }
})

export default DataSyncTaskContent
